import axios from 'axios';

const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || '/api/v1',
  headers: {
    'Content-Type': 'application/json',
  },
});

api.interceptors.request.use(
  (config) => {
    const token = "dfb798f07c6c470bb27b6c9f60bae27d.WskEnEcI7K8yetsxAoMetE9R7a0HBaiH";
    config.headers.Authorization = `Bearer ${token}`;
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export const uploadProductMaterial = async (userId: number, kbId: number, file: File, parserType: string = 'general') => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('kb_id', kbId.toString());
  formData.append('file', file);
  formData.append('parser_type', parserType);
  
  return api.post('/product-materials', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const uploadMethodologyMaterial = async (userId: number, file: File) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('file', file);
  
  return api.post('/methodology-materials', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const uploadScriptCaseMaterial = async (userId: number, file: File) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('file', file);
  
  return api.post('/script-case-materials', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const searchProductInfo = async (userId: number, query: string) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('query', query);
  
  return api.post('/product-search', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const getReferenceScripts = async (userId: number) => {
  return api.get('/reference-scripts', {
    params: { user_id: userId },
  });
};

export const generateScriptOutline = async (
  userId: number, 
  productDesc: string, 
  referenceScriptIds: number[] = []
) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('product_desc', productDesc);
  
  if (referenceScriptIds && referenceScriptIds.length > 0) {
    console.log('Adding reference_script_ids to FormData:', referenceScriptIds);
    referenceScriptIds.forEach(id => {
      formData.append('reference_script_ids', id.toString());
    });
    
    console.log('FormData entries:');
    for (let pair of formData.entries()) {
      console.log(pair[0], pair[1]);
    }
  }
  
  return api.post('/script-outlines', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const generateCompleteScript = async (
  userId: number, 
  productDesc: string, 
  scriptOutline: string | object, 
  referenceScriptIds: number[] = []
) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('product_desc', productDesc);
  
  const outlineStr = typeof scriptOutline === 'object' ? 
    JSON.stringify(scriptOutline) : scriptOutline;
  formData.append('script_outline', outlineStr);
  
  if (referenceScriptIds && referenceScriptIds.length > 0) {
    console.log('Adding reference_script_ids to CompleteScript FormData:', referenceScriptIds);
    referenceScriptIds.forEach(id => {
      formData.append('reference_script_ids', id.toString());
    });
    
    console.log('CompleteScript FormData entries:');
    for (let pair of formData.entries()) {
      console.log(pair[0], pair[1]);
    }
  }
  
  return api.post('/complete-scripts', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const saveCompleteScript = async (
  userId: number, 
  title: string, 
  content: string
) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('title', title);
  formData.append('content', content);
  
  return api.post('/complete-scripts/save', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const generateScriptFragment = async (
  userId: number, 
  productDesc: string, 
  scriptOutline: string | object, 
  currentSelection: string, 
  currentContent: string,
  userGeneratedRequest?: string, 
  referenceScriptIds: number[] = []
) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('product_desc', productDesc);
  
  const outlineStr = typeof scriptOutline === 'object' ? 
    JSON.stringify(scriptOutline) : scriptOutline;
  formData.append('script_outline', outlineStr);
  
  formData.append('current_selection', currentSelection);
  formData.append('current_content', currentContent);
  
  if (userGeneratedRequest) {
    formData.append('user_generated_request', userGeneratedRequest);
  }
  
  if (referenceScriptIds && referenceScriptIds.length > 0) {
    console.log('Adding reference_script_ids to ScriptFragment FormData:', referenceScriptIds);
    referenceScriptIds.forEach(id => {
      formData.append('reference_script_ids', id.toString());
    });
    
    console.log('ScriptFragment FormData entries:');
    for (let pair of formData.entries()) {
      console.log(pair[0], pair[1]);
    }
  }
  
  return api.post('/script-fragments', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const uploadCompleteScriptMaterial = async (userId: number, file: File) => {
  const formData = new FormData();
  formData.append('user_id', userId.toString());
  formData.append('file', file);

  return api.post('/complete-scripts_upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export default api;
